<template>
  <div class="msg" :class="{ 'is-user': role === 'user', 'is-assistant': role === 'assistant' }">
    <div class="msg__avatar">
      <img :src="avatarSrc" alt="avatar" />
    </div>
    <div class="msg__bubble">
      <PdfMessage v-if="type === 'SEND_PDF_FILE'" :url="content" :size="size" />
      <CardDrawingAnalysis v-else-if="type === 'SEND_CARD_DRAWING_ANALYSIS'" :data="content" />
      <div v-else>
        <!-- 包含reason和answer标签的特殊展示 -->
        <div v-if="rendered.hasReasonAnswer" class="msg__content">
          <!-- AI思考过程 -->
          <div v-if="rendered.reason" class="ai-thinking">
            <div class="ai-thinking__title">🤔 AI思考过程</div>
            <div class="ai-thinking__content markdown-content" v-html="rendered.reason"></div>
          </div>
          <!-- AI回答 -->
          <div v-if="rendered.answer" class="ai-answer markdown-content" v-html="rendered.answer"></div>
          <!-- 如果还在流式传输中且没有answer内容，显示加载提示 -->
          <div v-if="!rendered.isComplete && !rendered.answer" class="streaming-indicator">
            正在思考中...
          </div>
        </div>
        <!-- 普通内容展示 -->
        <div v-else class="msg__content markdown-content" v-html="rendered.content"></div>
        
        <!-- 复制按钮 - 仅普通文本类型显示 -->
        <button 
          class="copy-btn" 
          @click="copyContent"
          :class="{ 'copied': copyStatus === 'copied' }"
        >
          {{ copyStatus === 'copied' ? '✔' : '复制' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch, onBeforeUnmount } from 'vue';
import { marked } from 'marked';
import { useUserStore } from '../stores/user';
import PdfMessage from './PdfMessage.vue';
import CardDrawingAnalysis from './CardDrawingAnalysis.vue';

// 配置marked选项
marked.setOptions({
  breaks: true, // 支持换行
  gfm: true, // 启用GitHub风格的markdown
});

const props = defineProps({
  role: { type: String, default: 'assistant' },
  content: { type: String, default: '' },
  type: { type: String, default: 'text' },
  size: { type: Number, default: undefined },
  isHistory: { type: Boolean, default: false }
});

// 用户头像处理
const userStore = useUserStore();
const avatarSrc = computed(() => {
  if (props.role === 'assistant') return '/logo.jpg';
  const src = userStore.currentUser?.userAvatar;
  return (src && String(src).trim().length > 0) ? src : '/user-avatar.svg';
});

// 打字机效果实现
const TYPE_INTERVAL_MS = 24;
// 设置打字机效果的速度，值越大，速度越快
const TYPE_STEP = 1.5;
const displayText = ref('');
let typeTimerId = null;
let targetText = '';

function ensureTypeTimer() {
  if (typeTimerId) return;
  typeTimerId = setInterval(() => {
    if (displayText.value.length < targetText.length) {
      const nextLen = Math.min(targetText.length, displayText.value.length + TYPE_STEP);
      displayText.value = targetText.slice(0, nextLen);
      return;
    }
    clearInterval(typeTimerId);
    typeTimerId = null;
  }, TYPE_INTERVAL_MS);
}

watch(
  () => props.content,
  (val) => {
    if (props.role !== 'assistant' || props.isHistory) {
      console.log("isHistory:"+props.isHistory)
      // 非助手消息或历史消息直接显示完整内容
      displayText.value = val ?? '';
      return;
    }
    targetText = val ?? '';
    if (!typeTimerId) ensureTypeTimer();
  },
  { immediate: true }
);

onBeforeUnmount(() => { if (typeTimerId) clearInterval(typeTimerId); });

// 解析包含reason和answer标签的内容
const parseReasonAnswer = (text) => {
  // 检查是否包含reason开始标签，即使还没有完整的标签对
  const hasReasonStart = text.includes('<reason>');
  const hasAnswerStart = text.includes('<answer>');
  
  // 如果检测到reason或answer标签的开始，就认为这是一个特殊格式的消息
  if (hasReasonStart || hasAnswerStart) {
    const reasonMatch = text.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/);
    const answerMatch = text.match(/<answer>([\s\S]*?)(?:<\/answer>|$)/);
    
    return {
      hasReasonAnswer: true,
      reason: reasonMatch ? reasonMatch[1].trim() : '',
      answer: answerMatch ? answerMatch[1].trim() : '',
      isComplete: text.includes('</reason>') && text.includes('</answer>')
    };
  }
  
  return { hasReasonAnswer: false, content: text };
};

// 将文本转换为markdown HTML
const parseMarkdown = (text) => {
  try {
    return marked.parse(text || '');
  } catch (error) {
    console.error('Markdown解析错误:', error);
    // 如果markdown解析失败，回退到普通文本处理
    return (text || '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\n/g, '<br/>')
      .replace(/  /g, '&nbsp;&nbsp;');
  }
};

// 文本渲染处理
const rendered = computed(() => {
  //let text = props.role === 'assistant' ? displayText.value : (props.content || '');
  //TODO：修改抽卡分析结果的文案展示，不直接显示一大段的抽卡数据
  let text = '';
  // if(props.content.includes('UID')){
  //     //text = "抽卡分析结果如图所示。";
  // }else 
  if(props.role === 'assistant'){
      text = displayText.value;
  }else {
      text = props.content;
  }
  
  // 检查是否包含reason和answer标签
  const parsed = parseReasonAnswer(text || '');
  if (parsed.hasReasonAnswer) {
    return {
      hasReasonAnswer: true,
      reason: parseMarkdown(parsed.reason),
      answer: parseMarkdown(parsed.answer),
      isComplete: parsed.isComplete
    };
  }
  
  return {
    hasReasonAnswer: false,
    content: parseMarkdown(text)
  };
});

// 复制功能实现
const copyStatus = ref('default'); // default / copied

const copyContent = () => {
  // 获取实际要复制的文本内容（未经过HTML转义的原始文本）
  let textToCopy = props.role === 'assistant' ? displayText.value : (props.content || '');
  
  // 如果包含reason和answer标签，只复制answer部分
  const parsed = parseReasonAnswer(textToCopy);
  if (parsed.hasReasonAnswer) {
    textToCopy = parsed.answer;
  }
  
  // 使用Clipboard API复制文本
  navigator.clipboard.writeText(textToCopy).then(() => {
    // 显示"已复制"状态
    copyStatus.value = 'copied';
    // 2秒后恢复默认状态
    setTimeout(() => {
      copyStatus.value = 'default';
    }, 2000);
  }).catch(err => {
    console.error('复制失败:', err);
    // 降级处理：创建临时textarea元素实现复制
    const textarea = document.createElement('textarea');
    textarea.value = textToCopy;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    
    // 显示"已复制"状态
    copyStatus.value = 'copied';
    setTimeout(() => {
      copyStatus.value = 'default';
    }, 2000);
  });
};
</script>

<style scoped>
.msg { display: grid; grid-template-columns: 32px minmax(0, 1fr); gap: 4px; align-items: flex-start; margin: 8px 0; }
 .msg.is-user { grid-template-columns: minmax(0, 1fr) 32px; }
.msg.is-user .msg__avatar { order: 2; }
 .msg.is-user .msg__bubble { order: 1;justify-self: flex-end;}

.msg__avatar img { width: 28px; height: 28px; border-radius: 50%; border: 1px solid var(--border-color); background: #fff; }
.msg__bubble { max-width: 100%; min-width: 0; }
.msg__content {
  white-space: normal; word-break: break-word; overflow-wrap: anywhere; padding: 0px 6px; border-radius: 18px; line-height: 1.5;
  background: var(--assistant-bubble-bg); color: var(--text-primary); border: 1px solid var(--assistant-bubble-border);
  max-width: 100%;
  display: inline-block;
}
.msg.is-user .msg__content { 
  background: var(--user-bubble-bg); 
  border-color: var(--user-bubble-border);
  background: #edf3fe;
  border: none;
}


/* Markdown全局样式：内容过长显示滚动条 */
.markdown-content {
  overflow-x: scroll;
}

/* Markdown内容样式 */
.markdown-content h1, .markdown-content h2, .markdown-content h3, 
.markdown-content h4, .markdown-content h5, .markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content h1 { font-size: 1.5em; border-bottom: 1px solid #eee; padding-bottom: 8px; }
.markdown-content h2 { font-size: 1.3em; }
.markdown-content h3 { font-size: 1.1em; }

/* 段落样式 */
.markdown-content p {
  margin: 8px 0;
  line-height: 1.6;
}

/* 列表样式 */
.markdown-content ul, .markdown-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-content li {
  margin: 4px 0;
  line-height: 1.5;
}

/* 代码样式 */
.markdown-content code {
  background-color: rgba(175, 184, 193, 0.2);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9em;
}

.markdown-content pre {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 12px;
  overflow-x: scroll;
  margin: 12px 0;
  border: 1px solid #e1e4e8;
}

.markdown-content pre code {
  background: none;
  padding: 0;
  border-radius: 0;
  font-size: 0.85em;
}

/* 引用样式 */
.markdown-content blockquote {
  border-left: 4px solid #dfe2e5;
  padding-left: 16px;
  margin: 12px 0;
  color: #6a737d;
  font-style: italic;
}

/* 链接样式 */
.markdown-content a {
  color: #0366d6;
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
}

/* 表格样式 */
.markdown-content table {
  border-collapse: collapse;
  margin: 12px 0;
  width: 100%;
  display: block;
  max-width: 100%;
  overflow-x: auto;
}

.markdown-content th, .markdown-content td {
  border: 1px solid #dfe2e5;
  padding: 8px 12px;
  text-align: left;
  word-break: break-word;
  overflow-wrap: anywhere;
}

.markdown-content th {
  background-color: #f6f8fa;
  font-weight: 600;
}

/* 分隔线样式 */
.markdown-content hr {
  border: none;
  border-top: 1px solid #e1e4e8;
  margin: 16px 0;
}

/* 强调样式 */
.markdown-content strong {
  font-weight: 600;
}

.markdown-content em {
  font-style: italic;
}


/* 复制按钮样式 - 默认隐藏，悬停时显示 */
.copy-btn {
  margin-top: 4px;
  padding: 2px 8px;
  font-size: 12px;
  border: none;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.05);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.2s ease;
  opacity: 0;
  visibility: hidden;
}

/* 用户消息的复制按钮样式 */
.msg.is-user .copy-btn {
  background-color: rgba(255, 255, 255, 0.1);
  margin-left: auto;
  display: block;
}

/* 鼠标悬停在气泡上时显示复制按钮 */
.msg__bubble:hover .copy-btn {
  opacity: 1;
  visibility: visible;
}

/* 复制成功状态样式 */
.copy-btn.copied {
  background-color: rgba(255, 255, 255, 0.1);
}

.copy-btn:hover:not(.copied) {
  background-color: rgba(0, 0, 0, 0.1);
}

/* AI思考过程样式 */
.ai-thinking {
  margin-bottom: 8px;
  padding: 6px 10px;
  background-color: rgba(0, 0, 0, 0.03);
  border-radius: 12px;
  border-left: 2px solid #ccc;
}

.ai-thinking__title {
  font-size: 11px;
  color: #666;
  font-weight: 500;
  margin-bottom: 4px;
}

.ai-thinking__content {
  font-size: 12px;
  color: #888;
  line-height: 1.4;
  font-style: italic;
}

.ai-answer {
  line-height: 1.5;
}

/* 流式传输指示器样式 */
.streaming-indicator {
  font-size: 13px;
  color: #999;
  font-style: italic;
  padding: 8px 0;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 0.6; }
  50% { opacity: 1; }
}

/* 暗色主题下的样式 */
@media (prefers-color-scheme: dark) {
  .ai-thinking {
    background-color: rgba(255, 255, 255, 0.05);
    border-left-color: #555;
  }
  
  .ai-thinking__title {
    color: #aaa;
  }
  
  .ai-thinking__content {
    color: #999;
  }
  
  .streaming-indicator {
    color: #777;
  }

  /* 暗色主题下的markdown样式 */
  .markdown-content h1 {
    border-bottom-color: #444;
  }

  .markdown-content code {
    background-color: rgba(255, 255, 255, 0.1);
  }

  .markdown-content pre {
    background-color: #2d3748;
    border-color: #4a5568;
  }

  .markdown-content blockquote {
    border-left-color: #4a5568;
    color: #a0aec0;
  }

  .markdown-content a {
    color: #63b3ed;
  }

  .markdown-content th, .markdown-content td {
    border-color: #4a5568;
  }

  .markdown-content th {
    background-color: #2d3748;
  }

  .markdown-content hr {
    border-top-color: #4a5568;
  }
}
/* 让 Markdown 内容和图片在气泡内不超出 */
.markdown-content { overflow-wrap: anywhere; word-break: break-word; max-width: 100%; }
.markdown-content img { max-width: 100%; height: auto; }

</style>